import { Controller, App, Post, Body } from "@midwayjs/core";
import { Application } from "../interface.js";
import { failres, okres } from "../config/resUtil.js";
import { log } from "console";
import { cloneDeep, lodashMap as map } from "lodash-es";

@Controller("/api/user")
export class UserController {
  @App("koa")
  app: Application;

  @Post("/apis")
  async apis(@Body() body) {
    var funname = body?._name;
    var func = this?.[funname];
    if (!func) {
      return failres(funname + "404");
    }

    var _params = cloneDeep(body);
    delete _params._name;
    delete _params["模块"];

    var _func = func.bind(this);
    return _func(_params);


  }


  async getlist(body) {
    console.log("开始 列表 ");

    var query = this.app.db.select().from("tb_模块");

    if (body?.模块名称) {
      query.whereLike("模块名称", `%${body?.模块名称}%`);
    }
    return okres(await query);
  }

  async getbyitem(body) {
    console.log("开始 获取单个 ");
    var query = this.app.db.select("*").from("tb_模块");
    console.log("body :", body);


    if ((!body) || !Object.keys(body).length) {
      return okres([]);
    }

    if (body?.id) {
      query.where("id", body?.id);
    } else {
      if (body?.模块名称) {
        query.whereLike("模块名称", `%${body?.模块名称}%`);
      }
    }


    console.log("query :", query);

    var lists = await query;
    var one = lists?.[0];

    return okres(one);
  }

  async 删除(body) {
  if(!body.id){;
  return failres('没有id')
  }
    var delresult = await this.app.db('tb_模块').where('id', body.id).del();
    return okres(delresult);
  }

  async addorupdate(body) {
    console.log("开始 新增or修改 ");
    var rsiltonme = await this.getbyitem(body);
    var one = rsiltonme && rsiltonme.data;
    console.log("one :", one);

    var result = undefined;
    if (one?.id) {
      var __params=cloneDeep(body)
      delete __params.id
      result = await this.app.db("tb_模块").where("id", '=',one.id).update(__params);
    } else {
      // 新增
      result = await this.app.db("tb_模块").insert(body);
    }
    return okres(result);
  }


}
